package websocket

import (
	"context"
	"fmt"

	"github.com/gogf/gf/v2/encoding/gjson"
	"github.com/gogf/gf/v2/util/gconv"

	"github.com/beherochuling/beesoft_api/app/helper/net"
)

var api = &apiService{
	ctx: context.Background(),
}

type apiService struct {
	ctx context.Context
}

func (r *apiService) DoSendMessages(address string, data *clusterSendMessageObject) error {
	_, err := r.doActions(address, &clusterAction{
		Action: clusterActionSendMessage,
		Data:   data,
	})
	return err
}
func (r *apiService) DoGetUsers(address string, groupId string) ([]int, error) {
	body, err := r.doActions(address, &clusterAction{
		Action: clusterActionGetUsers,
		Data:   groupId,
	})
	if err != nil {
		return nil, err
	}

	var res *JsonObject
	err = gconv.Struct(body, &res)
	if err != nil {
		return nil, err
	}

	return gconv.Ints(res.Data), nil
}
func (r *apiService) DoCheckExists(address string, data *clusterCheckExistsObject) (bool, error) {
	body, err := r.doActions(address, &clusterAction{
		Action: clusterActionCheckExists,
		Data:   data,
	})
	if err != nil {
		return false, err
	}

	var res *JsonObject
	err = gconv.Struct(body, &res)
	if err != nil {
		return false, err
	}

	j := gjson.New(res.Data)
	exists := j.Get("exists", false).Bool()
	return exists, nil
}
func (r *apiService) DoCloseConnection(address string, data *clusterCloseConnectionObject) error {
	_, err := r.doActions(address, &clusterAction{
		Action: clusterActionCloseConnection,
		Data:   data,
	})
	return err
}

func (r *apiService) doActions(address string, data *clusterAction) (body string, err error) {
	uri := fmt.Sprintf("http://%s%s/actions", address, uriPrefixFramework)

	body = net.NewHttp(r.ctx).
		SetTimeout(cluster.serviceTimeout).
		SetContentTypeJson().
		Post(uri, data)
	// if err != nil {
	// 	glog.Error(ctx, err, uri, gconv.String(data))
	// }

	return body, err
}
